import _ from 'lodash'

export const list2JsonTree = (data, options) => {
  const mainKey = (options && options.mainKey) || 'id'
  const parentKey = (options && options.parentKey) || 'parentId'
  const sortKey = (options && options.sortKey) || 'seq'
  const childListKey = (options && options.childListKey) || 'children'
  const dataKey = (options && options.dataKey) || 'data'

  let idItemMap = {}
  data = _.map(data, one => {
    let res = {}
    res[dataKey] = _.cloneDeep(one)
    res[childListKey] = []
    idItemMap[res[dataKey][mainKey]] = res
    return res
  })
  let res = []

  _.each(data, one => {
    let oneData = one[dataKey]
    if (oneData[parentKey] && idItemMap[oneData[parentKey]]) {
      idItemMap[oneData[parentKey]][childListKey].push(one)
    } else {
      res.push(one)
    }
  })
  // 排序
  return sortJsonTree(res, sortKey, dataKey)
}

export const sortJsonTree = (data, key, dataKey) => {
  let res = _.sortBy(data, one => one[dataKey][key])
  _.each(data, function (one) {
    if (one.children) {
      one.children = sortJsonTree(one.children, key, dataKey)
    }
  })
  return res
}

export function jsonTree2list(data, options, parentId) {
  const mainKey = (options && options.mainKey) || 'id'
  const parentKey = (options && options.parentKey) || 'parentId'
  const sortKey = (options && options.sortKey) || 'seq'
  const childListKey = (options && options.childListKey) || 'children'
  const dataKey = (options && options.dataKey) || 'data'

  let res = []
  _.each(data, function (one, index) {
    if (parentId) {
      one[dataKey][parentKey] = parentId
    }
    res.push(one[dataKey])
    if (one[dataKey][sortKey] === undefined) {
      one[dataKey][sortKey] = index + 1
    }

    if (one[childListKey]) {
      res = res.concat(jsonTree2list(one[childListKey], options, one[mainKey]))
    }
  })
  return res
}

export function getItemById(data, id) {
  let item
  _.each(data, one => {
    if (one.id === id) {
      item = one
      return false
    } else {
      item = getItemById(one.children, id)
      return !item
    }
  })
  return item
}

export function getItemsBy(data, fn, items) {
  if (!items) {
    items = []
  }
  _.each(data, one => {
    if (fn(one)) {
      items.push(one)
    }
    getItemsBy(one.children, fn, items)
  })
  return items
}

// let testData = [
//   {id: 1, parentId: 0, name: '1', seq: '2'},
//   {id: 2, parentId: 0, name: '2', seq: '4'},
//   {id: 3, parentId: 0, name: '3', seq: '3'},
//   {id: 4, parentId: 0, name: '4', seq: '1'},
//   {id: 5, parentId: 1, name: '11', seq: '2'},
//   {id: 6, parentId: 1, name: '12', seq: '3'},
//   {id: 7, parentId: 1, name: '13', seq: '1'},
//   {id: 8, parentId: 2, name: '21', seq: '2'},
//   {id: 9, parentId: 2, name: '22', seq: '1'},
// ]
// let a = JSON.stringify(list2JsonTree(testData), 0, 2)
// console.log(a)
// let b = JSON.stringify(jsonTree2list(JSON.parse(a)),0,2)
// console.log(b)-+
